package com.xlh.Utils;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EncodingUtils;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.util.Log;

/**
 * @author Fang
 * @date 2010-11-6 工具￿
 */
@SuppressWarnings({ "unchecked" })
public final class FUti {

	// ByteBufUtil是ByteBuf的工具类，它提供了一系列的静态方法来操作ByteBuf￿
	// http://www.cnblogs.com/xianyijun/p/5432884.html
	/**
	 * N个线程会使用该块,考虑同步￿以及使用前销￿ bytebuf
	 * http://www.cnblogs.com/zemliu/p/3375000.html
	 */

	/**
	 * 获取安卓版本
	 * 方法功能说明＿
	 * 创建＿016-9-23 by fang
	 * 修改：日朿by 修改耿
	 * 修改内容＿
	 * @参数＿@return
	 * @return int
	 * @throws
	 */
	public static String getSDKVersionNumber() {
		String sdkVersion;
		try {
			//  sdkVersion = Integer.valueOf(android.os.Build.VERSION.SDK);
			sdkVersion = String.valueOf(android.os.Build.VERSION.SDK);
		} catch (NumberFormatException e) {
			sdkVersion = "";
		}
		return sdkVersion;
	}

	//assect读取
	public static String readAssect(Context context,String file) {
		InputStream is = null;
		String msg = null;
		try {
			is = context.getResources().getAssets().open(file);
			byte[] bytes = new byte[is.available()];
			is.read(bytes);
			msg = new String(bytes);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return msg;
	}



	public static boolean checkPermission(Context contxt,String permissionString){

		PackageManager pm = contxt.getPackageManager();
		boolean permission = (PackageManager.PERMISSION_GRANTED ==
				pm.checkPermission("android.permission."+permissionString, "com.xlh.outside"));
		if (permission) {
			return true;
		}else {
			return false;
		}

	}



	public static String posturl(String url){
		InputStream is = null;
		String result = "";

		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}catch(Exception e){
			return "Fail to establish http connection!"+e.toString();
		}

		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				//sb.append(line + "\n");
				sb.append(line);
			}
			is.close();

			result=sb.toString();
		}catch(Exception e){
			return "Fail to convert net stream!";
		}

		return result;
	}
	// 打印
	public static void P(String s) {
		// System.out.println(SysConf.PTAG+s);
	}

	/**
	 * final Activity activity ：调用该方法的Activity实例 long milliseconds ：震动的时长，单位是毫秒
	 * long[] pattern ：自定义震动模式 。数组中数字的含义依次是[静止时长，震动时长，静止时长，震动时长䀣䀝时长的单位是毫秒
	 * boolean isRepeat ＿是否反复震动，如果是true，反复震动，如果是false，只震动丿̡
	 */

	public static void Vibrate(final Activity activity, long milliseconds) {
		Vibrator vib = (Vibrator) activity
				.getSystemService(Service.VIBRATOR_SERVICE);
		vib.vibrate(milliseconds);
	}

	public static void Vibrate(final Activity activity, long[] pattern,
							   boolean isRepeat) {
		Vibrator vib = (Vibrator) activity
				.getSystemService(Service.VIBRATOR_SERVICE);
		vib.vibrate(pattern, isRepeat ? 1 : -1);
	}

	public static void GetOnlyCode(Context activityCtx) {

		// TelephonyManager TelephonyMgr =
		// (TelephonyManager)activityCtx.getSystemService(TelephonyManager.);
		// String szImei = TelephonyMgr.getDeviceId();
		// WifiManager wm =
		// (WifiManager)activityCtx.getSystemService(Context.WIFI_SERVICE);
		// String m_szWLANMAC = wm.getConnectionInfo().getMacAddress();
	}

	public static String searchFile(String keyword) {
		String result = "";
		File[] files = new File("/").listFiles();
		for (File file : files) {
			if (file.getName().indexOf(keyword) >= 0) {
				result += file.getPath() + "\n";
			}
		}
		if (result.equals("")) {
			result = "找不到文仿!";
		}
		return result;
	}

	/**
	 * 棿ߥ应用下的文件是否存在
	 * 方法功能说明＿
	 * 创建＿016-9-13 by fang
	 * 修改：日朿by 修改耿
	 * 修改内容＿
	 * @参数＿@param keyword
	 * @参数＿@return
	 * @return Boolean
	 * @throws
	 */
	public static Boolean CheckFile(String keyword) {
		boolean flag = false;
		File[] files = new File("/").listFiles();
		String result = "";
		for (File file : files) {
			if (file.getName().indexOf(keyword) >= 0) {
				result += file.getPath() + "\n";
			}
		}
		if (!result.equals("")) {
			flag = true;
		}
		return flag;
	}




	public static void CreateKey(Context ctx) throws Exception{

		String keyFile = "wujikey.txt";
		String file = ctx.getFilesDir().getPath();
		String filePath =file +"/"+keyFile ;
		File f = new File(filePath);

		if (!f.exists())
		{
			String s = FUti.md5(FUti.getRandomString(12));
			FUti.writeDateFile(ctx, keyFile, s.getBytes());

		}
		//String key = FUti.readDateFile(ctx, keyFile);

	}


	public static void writeFileData(Context ctx,String file,String txt) throws Exception{


		String dir = ctx.getFilesDir().getPath();
		String filePath =dir +"/"+file ;
		File f = new File(filePath);

		if (!f.exists())
		{
			String s = FUti.md5(FUti.getRandomString(12));
			//FUti.writeDateFile(ctx, keyFile, s.getBytes());

		}
		//String key = FUti.readDateFile(ctx, keyFile);

	}










	public static String md5(String txt) throws Exception{

		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(txt.getBytes("utf-8"));    //问题主要出在这里，Java的字符串是unicode编码，不受源码文件的编码影响；逐HP的编码是和源码文件的编码丿Ǵ，受源码编码影响〿
		StringBuffer buf=new StringBuffer();
		for(byte b:md.digest()){
			buf.append(String.format("%02x", b&0xff));
		}
		return  buf.toString();

	}

	/**
	 * 生成随机字符
	 * 方法功能说明＿
	 * 创建＿016-9-13 by fang
	 * 修改：日朿by 修改耿
	 * 修改内容＿
	 * @参数＿@param length
	 * @参数＿@return
	 * @return String
	 * @throws
	 */
	public static String getRandomString(int length) { //length表示生成字符串的长度
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	// 将文件写入应用的data/data的files目录丿
	public static void writeDateFile(Context ctx,String fileName, byte[] buffer) throws Exception {
		byte[] buf = fileName.getBytes("iso8859-1");
		fileName = new String(buf, "GBK");
		// Context.MODE_PRIVATE：为默认操作模式，代表该文件是私有数据，只能被应用本身访问，在该模式下，写入的内容会覆盖原文件的内容，如果想把新写入的内容追加到原文件中。可以使用Context.MODE_APPEND
		// Context.MODE_APPEND：模式会棿ߥ文件是否存在，存在就徿և件追加内容，否则就创建新文件〿
		// Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件〿
		// MODE_WORLD_READABLE：表示当前文件可以被其他应用读取；MODE_WORLD_WRITEABLE：表示当前文件可以被其他应用写入〿
		// 如果希望文件被其他应用读和写，可以传入：
		// openFileOutput("output.txt", Context.MODE_WORLD_READABLE +
		// Context.MODE_WORLD_WRITEABLE);
		FileOutputStream fos = ctx.openFileOutput(fileName,
				Context.MODE_PRIVATE);// 添加在文件后靿
		fos.write(buffer);
		fos.close();
	}

	// 读取应用的data/data的files目录下文件数捿
	public static String readDateFile(Context ctx,String fileName) throws Exception {





		FileInputStream fis = ctx.openFileInput(fileName);
		String result = FUti.streamRead(fis);// 返回丿ت字符丿
		return result;
	}
	private static String streamRead(InputStream is) throws IOException {
		int buffersize = is.available();// 取得输入流的字节长度
		byte buffer[] = new byte[buffersize];
		is.read(buffer);// 将数据读入数绿
		is.close();// 读取完毕后要关闭流㿠
		String result = EncodingUtils.getString(buffer, "UTF-8");// 设置取得的数据编码，防止乱码
		return result;
	}

	/**
	 * INT转小端字节序 int to byte[] 支持 1或迠4 个字芿
	 *
	 * @param i
	 * @param len
	 * @return
	 */
	public static byte[] intToByteSml(int i, int len) {
		byte[] abyte = null;
		if (len == 1) {
			abyte = new byte[len];
			abyte[0] = (byte) (0xff & i);
		} else {
			abyte = new byte[len];
			abyte[0] = (byte) ((i >>> 24) & 0xff);
			abyte[1] = (byte) ((i >>> 16) & 0xff);
			abyte[2] = (byte) ((i >>> 8) & 0xff);
			abyte[3] = (byte) (i & 0xff);
		}
		return abyte;
	}

	/**
	 * 小端byte转int
	 *
	 * @param bytes
	 * @return
	 */
	public static int SmlbytesToInt(byte[] bytes) {
		int addr = 0;
		if (bytes.length == 1) {
			addr = bytes[0] & 0xFF;
		} else {
			addr = bytes[0] & 0xFF;
			addr = (addr << 8) | (bytes[1] & 0xff);
			addr = (addr << 8) | (bytes[2] & 0xff);
			addr = (addr << 8) | (bytes[3] & 0xff);
		}
		return addr;
	}

	/**
	 * int 转byte
	 *
	 * @param res
	 * @return
	 */
	public static byte[] int2bytebig(int res) {
		byte[] targets = new byte[4];

		targets[0] = (byte) (res & 0xff);// ￿��￿
		targets[1] = (byte) ((res >> 8) & 0xff);// 次低￿
		targets[2] = (byte) ((res >> 16) & 0xff);// 次高￿
		targets[3] = (byte) (res >>> 24);// ￿��￿无符号右移�?
		return targets;
	}

	/**
	 * byte 转int
	 *
	 * @param res
	 * @return
	 */
	public static int bigbyte2int(byte[] res) {
		// ￿��byte数据左移24位变￿x??000000，再右移8位变￿x00??0000

		int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00) // | 表示安位￿
				| ((res[2] << 24) >>> 8) | (res[3] << 24);
		return targets;
	}

	private static Random random = new Random();

	private static long timeBegin = 0;

	public static int gmChangeDay;

	private static Map<String, Class<?>> classInstance = new HashMap<String, Class<?>>();

	public static SimpleDateFormat fomart = new SimpleDateFormat(
			"yyyy--MM--dd HH:mm");

	static {
		Calendar cal = Calendar.getInstance();
		cal.set(2010, 1, 1);
		timeBegin = cal.getTimeInMillis();
	}

	private FUti() {
	}

	public static int getRandom(int n) {
		return getRandom(0, n);
	}

	public static int getRandom(int n1, int n2) {
		if (n2 > n1) {
			if (n2 == n1 + 1)
				return n1;
			return (Math.abs(random.nextInt()) % (n2 - n1) + n1);
		} else if (n1 > n2) {
			if (n1 == n2 + 1)
				return n2;
			return (Math.abs(random.nextInt()) % (n1 - n2) + n2);
		} else
			return n1;
	}

	public static float getRandom(float n1, float n2) {
		if (n2 > n1) {
			if (n2 == n1 + 1)
				return n1;
			return (Math.abs(random.nextFloat()) % (n2 - n1) + n1);
		} else if (n1 > n2) {
			if (n1 == n2 + 1)
				return n2;
			return (Math.abs(random.nextFloat()) % (n1 - n2) + n2);
		} else
			return n1;
	}

	public static double getRandom(double n1, double n2) {
		if (n2 > n1) {
			if (n2 == n1 + 1)
				return n1;
			return (Math.abs(random.nextDouble()) % (n2 - n1) + n1);
		} else if (n1 > n2) {
			if (n1 == n2 + 1)
				return n2;
			return (Math.abs(random.nextDouble()) % (n1 - n2) + n2);
		} else
			return n1;
	}

	public static void delay(long millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static int currentTimeSecond() {
		return (int) ((System.currentTimeMillis() - timeBegin) / 1000);
	}

	public static int timeSecond(long timeMillis) {
		return (int) ((timeMillis - timeBegin) / 1000);
	}

	public static long timeMillis(long timeSecond) {
		return timeSecond * 1000 + timeBegin;
	}

	public static Object loadObject(String name) {
		return loadObject(name, null);
	}

	public static Object loadObject(String name, ClassLoader loader) {
		try {
			Class c = classInstance.get(name);
			if (c == null) {
				c = (loader != null) ? loader.loadClass(name) : Class
						.forName(name);
				classInstance.put(name, c);
			}
			return c.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static int getWordCount(String s) {
		int length = 0;
		for (int i = 0; i < s.length(); i++) {
			int ascii = Character.codePointAt(s, i);
			if (ascii >= 0 && ascii <= 255)
				length++;
			else
				length += 2;
		}
		return length;
	}

	public static void randomArray(Object[] obs, int begin, int end) {
		int r = 0;
		Object ob = null;
		for (int i = begin; i < end; i++) {
			r = getRandom(begin, end);
			ob = obs[i];
			obs[i] = obs[r];
			obs[r] = ob;
		}
	}

	public static void randomArray(Object[] obs) {
		randomArray(obs, 0, obs.length);
	}

	public static void randomList(List list) {
		int r = 0;
		int size = list.size();
		for (int i = 0; i < size; i++) {
			r = getRandom(0, size);
			Object obI = list.get(i);
			Object obR = list.get(r);
			list.set(i, obR);
			list.set(r, obI);
		}
	}

	public static void randomFabaoList(List list) {
		int r = 0;
		int size = list.size() - 1;
		Object obI = null;
		Object obR = null;
		for (int i = size - 1; i >= 0; i--) {
			r = getRandom(0, i);
			obI = list.get(r);
			obR = list.get(size);
			list.set(size, obI);
			list.set(i, obR);
			size--;
		}
	}

	public static int todayMills(long mill) {
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(mill);
		return (cal.get(Calendar.HOUR_OF_DAY) * 3600 + cal.get(Calendar.MINUTE)
				* 60 + cal.get(Calendar.SECOND))
				* 1000 + cal.get(Calendar.MILLISECOND);
	}

	public static int todayWeekDay(long mill) {
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(mill);
		return cal.get(Calendar.DAY_OF_WEEK);
	}

	/**
	 *
	 * @param mill
	 * @return
	 */
	public static int[] getDateInfo() {
		int dateInfo[] = new int[3];
		Calendar cal = Calendar.getInstance();
		// cal.add(Calendar.DATE, gmChangeDay);
		dateInfo[0] = cal.get(Calendar.YEAR);
		dateInfo[1] = cal.get(Calendar.MONTH) + 1;
		dateInfo[2] = cal.get(Calendar.DAY_OF_MONTH);
		return dateInfo;
	}

	/**
	 */
	public static int[] getWeekInfo() {
		int weekInfo[] = new int[3];
		Calendar cal = Calendar.getInstance();
		cal.setFirstDayOfWeek(Calendar.MONDAY);
		weekInfo[0] = cal.get(Calendar.YEAR);
		weekInfo[1] = cal.get(Calendar.WEEK_OF_YEAR);
		weekInfo[2] = cal.get(Calendar.DAY_OF_WEEK);
		// ����������￿
		if (weekInfo[2] - 1 == 0) {
			weekInfo[2] = 7;
		} else {
			weekInfo[2] = weekInfo[2] - 1;
		}
		return weekInfo;
	}

	/**
	 *
	 * @param mill
	 * @return
	 */
	public static int getCurrentMonth() {
		Calendar cal = Calendar.getInstance();
		return cal.get(Calendar.MONTH) + 1;
	}

	/**
	 *
	 * @return
	 */
	public static int getCurrentMonthDay() {
		Calendar cal = Calendar.getInstance();
		// cal.add(Calendar.DATE, gmChangeDay);
		return cal.get(Calendar.DAY_OF_MONTH);
	}

	public static List<String> getIpList() {
		try {
			List<String> ipList = new ArrayList<String>();
			Enumeration<NetworkInterface> faces = NetworkInterface
					.getNetworkInterfaces();
			while (faces.hasMoreElements()) {
				NetworkInterface ni = (NetworkInterface) faces.nextElement();
				Enumeration<InetAddress> ips = ni.getInetAddresses();
				while (ips.hasMoreElements()) {
					InetAddress inetAddress = (InetAddress) ips.nextElement();
					String host = inetAddress.getHostAddress();
					if (host.equals("127.0.0.1")) {
						continue;
					}
					ipList.add(host);
				}
			}
			return ipList;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static boolean ipMatch(String regix) {

		List<String> ipList = getIpList();
		for (String host : ipList) {
			Pattern p = Pattern.compile(regix);
			Matcher m = p.matcher(host);
			System.err.println("GM ALLOW IP-->" + regix);
			System.err.println("GM HOST-->" + host);
			if (m.find()) {
				System.err.println("GM FIND-->" + true);
				return true;
			}
		}
		return false;
	}

	/**
	 */
	public static String getCurrDate() {
		Calendar calendar = Calendar.getInstance();
		return new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
	}

	/**
	 */
	public static String getCurrDateTime() {
		Calendar calendar = Calendar.getInstance();
		return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(calendar
				.getTime());
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// int t = 1000 * 60 * 60 * 24;
		// System.out.println(getCurrDateTime());
		// getWeekInfo();
		System.out.println(URLEncoder.encode("fang"));
	}

	/**
	 */
	public static int getDaySum(int year) {
		int sum = 0;
		GregorianCalendar gre = new GregorianCalendar();
		if (gre.isLeapYear(year)) {
			// ������
			sum = 366;
		} else {
			sum = 365;
		}
		return sum;
	}

	public static String getTimeFormat(Date date) {
		return fomart.format(date);
	}

	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}





}